<!-- 文件翻译 -->
<!-- 带翻译列表 -->
<!--  -->
<template>
  <div class="file-container">
    <ul class="select-file">
      <li :class="selectFile===item?'acitve':''" v-for="item in trans_file" class="item" @click="selectFile=item">{{ item }}
        <el-button style="float:right" type="text" size="small" @click="deleteFile(item)">删除</el-button>
       
      </li>
    </ul>
    <el-upload
        class="upload-demo"
        drag
        :multiple="false"
        :limit="1"
        ref="fileUpload"
     
        :action="uploadParams.uploadUrl"
        :data="uploadParams.data"
         :headers="uploadParams.headers"
        :file-list="uploadParams.fileLists"
        :on-success="handleSuc"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :on-change="changeFile"
      >
        <i class="el-icon-plus"></i>
    </el-upload>
    <div class="chat-btn-line"> 
      <el-button class="chat-btn" size="small" type="primary" @click="sendtext()">提问</el-button>
      <el-button class="chat-btn" size="small"  @click="changeFileType()">返回文本翻译</el-button>
    </div>


   </div>
</template>

<script>
import { getData, postData } from '@/service/getData';
import axios from 'axios';
import { fetchEventSource } from '@microsoft/fetch-event-source';
export default {
  data() {
    return {
      selectFile:'',
        trans_file:[],
        uploadShow: false,
        loading: false,
        uploadParams: {
          uploadUrl: '/agent/translate/upload_trans_orifile',
          data: {},
          headers:{
            'Authorization':''
          },
          name: 'file',
          fileLists: [],
        },
    }
  },
  props:{
    fileName: {
      type: String,
      default: null
    }
  },
  mounted() {
    // 接收父组件传来的参数fileName
    let token = localStorage.getItem('token')
    this.uploadParams.headers['Authorization'] ='Token '+token;

    this.getFileList()
  },
  methods: {
    // 提交文件 获取taskid  

    // 删除文件
    // 切换成翻译类型 
    changeFileType(){
      this.$emit('change-parent');
    },
    sendtext(){
      var _this = this;
      if(!this.selectFile){
        _this.$message({
          message: '请选选择文件',
          type: 'warning',
        });
        return
      }
      axios.post('/agent/translate/trans_file', {
          glossary_file_name:_this.fileName,
          trans_orifile_name: _this.selectFile,
        },{
          headers:{
            'Authorization': _this.uploadParams.headers['Authorization']
          }
        })
        .then((res) => {
          if (res.data.status === 200) {
            _this.$emit('call-parent','选择文件：'+_this.selectFile+'进行翻译',false)
            _this.handleChatSubmit2(res.data.task_id, 'agent/translate/trans_file_sse');
          } else {
            _this.messages[_this.messages.length - 1].text = '服务开小差了，请稍后重试';
          }
        });
    },
    downloadFile(task_id) {
      var _this = this;
      axios
      .post(
        '/agent/translate/download_trans_file',
        {
          task_id,
        },
        {
          headers:{
            Authorization: this.uploadParams.headers['Authorization']
          },
          responseType: 'blob', // 关键配置
        },
      )
      .then((res) => {
        if(!res.data.code){
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const a = document.createElement('a');
          // 3. 设置文件名（示例为.docx，按需修改）
          a.download = '文件.docx';
          // 4. 创建一个链接元素
          a.href = url;
          a.click();
          // 将元素添加转换成html 片段
         
          window.URL.revokeObjectURL(url);
          _this.$emit('call-parent','已帮您自动下载该文档。',true);
        }else{
          _this.$emit('call-parent',res.data.error,false);
        }
      })
    },
    handleChatSubmit2(id,str) {
      
        let _this = this;
        let sliceText='.'
        const controller = new AbortController();
      //agent/corrector/correct_sse
        // 'agent/meeting/summarize_sse'
        fetchEventSource(str, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Authorization': this.uploadParams.headers['Authorization'],
            Accept: ['text/event-stream', 'application/json'],
          },
          body: JSON.stringify({
            task_id: id,
          }),
          openWhenHidden: true,
          signal: controller.signal, //与其相关联的signal属性
          onopen(e) {
            _this.$emit('call-parent',"接口调用成功",false);
          },
          onmessage(msg, event) {
            // 获取
            console.log('收到消息:', msg, event);
            if (msg.event === 'completed') {
              // 下载文件
              _this.downloadFile(id);
            }else if(msg.event === 'waiting'){
              sliceText+='.'
              _this.$emit('call-parent',msg.data + sliceText,true);
            }
          },
          onclose(e) {
            controller.abort();
          },
          onerror(err) {
            controller.abort();
          },
        });
      
    },
    // 获取文件列表
    getFileList() {
      postData(
        '/agent/translate/list_trans',
        {

        },
        'post',
        {
          headers: { 'Content-Type': 'application/json;charset=UTF-8' },
          'Authorization': this.uploadParams.headers['Authorization']
        },
      ).then((res) => {
        // 成功后跳转到登录页
        this.trans_file = res.files
      });
    },
    // 删除文件
    deleteFile(trans_file_name) {
      postData(
        '/agent/translate/drop_trans',
        {
          trans_file_name
        },
        'post',
        {
          headers: { 
            'Content-Type': 'application/json;charset=UTF-8',
            'Authorization': this.uploadParams.headers['Authorization']
           },
        },
      ).then((res) => {
        // 成功后跳转到登录页
        if(this.selectFile===trans_file_name){
          this.selectFile=''
        }
        this.getFileList()
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning('超出1个文件，请先删除当前文件，再重新上传');
      return false;
    },
    changeFile(file, fileList) {
      this.uploadParams.data = {
        file_name: file.name,
      };
    },
    handleError(err, file, fileList) {
      if (err.status == 409) {
        // 上传失败处理
        this.$message({
          message: '文件已存在，请勿重复上传。',
          type: 'warning',
        });
      } else if (err.status == 504) {
        // 上传失败处理
        this.$message({
          message: '文件较大，后台处理中，稍后请刷新查看。',
          type: 'warning',
        });
      } else {
        // 上传失败处理
        this.$message({
          message: '上传失败，请重新上传文件或联系管理员' /*  */,
          type: 'error',
        });
      }
      this.beforeClose();
    },
    closeUpload() {
      this.loading = false;
      this.uploadShow = false;
      this.$refs.fileUpload.abort();
      this.$message.warning('取消上传');
    },
    handleSuc(res, file, fileList) {
      this.uploadShow = false;
      this.loading = false;
      // 上传成功处理
      if (res && res.status == 200) {
        this.uploadShow = false;
        this.$message({
          message: '上传文件成功',
          type: 'success',
        });
        this.$set(this.uploadParams, 'fileLists', []);
        this.getFileList()
    
      } else {
        // 上传失败处理
        this.$message({
          message: res.message,
          type: 'error',
        });
        this.beforeClose();
      }
    },
    beforeClose() {
      // debugger
      this.loading = false;
      this.uploadShow = false;
      this.$set(this.uploadParams, 'fileLists', []);
      this.$forceUpdate();
    },
    uploadForm() {
      this.$refs.fileUpload.submit();
      this.loading = true;
    },
    uploadFile() {
      this.uploadParams.data = {
        file_name: '',
      };
      this.uploadShow = true;
      this.$set(this.uploadParams, 'fileLists', []);
      this.$forceUpdate();
    },
  }
}
</script>

<style lang="scss" scoped>
.file-container {
  width: 100%;
  height: 200px;
  background-color: #fff;
  display: block;
  position: absolute;
  bottom: 14px;
  left: 0;
  z-index: 999;
  border-radius: 4px;
  box-sizing: border-box;
  padding: 10px;
}
.select-file {
  padding: 0;
  margin: 0; 
  height: 50px;
  overflow-y: auto;
}
.item{
  background-color: #e5f3ff;
  display: inline-block;
  width: 240px;
  margin: 0 20px 0 0;
  padding: 4px 10px;
  font-size: 12px;
  border: 1px solid #7184e0;
  line-height: 30px;
  cursor: pointer;
  border-radius: 4px;
}
.acitve{
  background-color: #82acec;
  border: 1px solid #7184e0;
}
.chat-btn-line{
  padding-top: 10px;
  .chat-btn{
    float: right;
    margin-right: 10px;
  }
}
</style>